package com.sevensoft.framework.beans;


import java.util.Iterator;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户存储和管理多个Property对象
 */
public class MutablePropertyValues implements Iterable<PropertyValue> {

    private final List<PropertyValue> propertyValueList;

    public MutablePropertyValues() {
        propertyValueList = new ArrayList<>();
    }

    public MutablePropertyValues(List<PropertyValue> propertyValueList) {
        if ( Objects.isNull(propertyValueList) )
            this.propertyValueList = new ArrayList<>();
        else
            this.propertyValueList = propertyValueList;
    }

    /**
     * 获取所有的PropertyValue对象，返回数组
     *
     * @return
     */
    public PropertyValue[] getPropertyValues() {
        return propertyValueList.toArray(new PropertyValue[0]);
    }

    public PropertyValue getPropertyValue(String name) {
        List<PropertyValue> collect = propertyValueList.stream()
                .filter(p -> p.getName().equals(name))
                .collect(Collectors.toList());
        return collect.get(0);
    }

    public boolean isEmpty() {
        return propertyValueList.isEmpty();
    }

    public MutablePropertyValues add(PropertyValue propertyValue) {
        for ( int i = 0; i < propertyValueList.size(); i++ ) {
            if ( propertyValueList.get(i).getName().equals(propertyValue.getName()) ) {
                propertyValueList.set(i, propertyValue);
                return this;
            }
        }
        this.propertyValueList.add(propertyValue);
        return this;
    }

    public boolean contains(String name) {
        return propertyValueList.stream()
                .anyMatch(propertyValue -> propertyValue.getName().equals(name));
    }

    /**
     * Returns an iterator over elements of type {@code T}.
     *
     * @return an Iterator.
     */
    @Override
    public Iterator<PropertyValue> iterator() {
        return propertyValueList.iterator();
    }
}
